package leetcode;

import java.util.Stack;

public class sanbaijiushisi {
    public static String decodeString(String s) {
        Stack<String> stack1=new Stack();
        Stack<Integer> stack2=new Stack();
        // 先给stack1放入" "
        stack1.push(" ");
        for(int i=0;i<s.length();i++){
            if(Character.isDigit(s.charAt(i))){
                int tmp=0;
                while(i<s.length()&&Character.isDigit(s.charAt(i))){
                    tmp=tmp*10+(s.charAt(i)-'0');
                    i++;
                }
                i--;
                stack2.push(tmp);
                continue;
            }
            if(s.charAt(i)=='['){
                StringBuffer stringbuffer=new StringBuffer();
                while(i<s.length()&&Character.isLowerCase(s.charAt(i+1))){
                    stringbuffer.append(s.charAt(i+1));
                    i++;
                }
                // i--;  经分析得这里不要i--;
                stack1.push(stringbuffer.toString());
                continue;
            }
            if(s.charAt(i)==']'){
                String p=stack1.pop();
                int q=stack2.pop();
                StringBuffer stringbuffer1=new StringBuffer();
                for(int m=0;m<q;m++){
                    stringbuffer1.append(p);
                }
                String s1=stack1.pop()+stringbuffer1.toString();
                stack1.push(s1);
                continue;
            }
            //正常情况
            StringBuffer stringbuffer2=new StringBuffer();
            while(i<s.length()&&Character.isLowerCase(s.charAt(i))){
                stringbuffer2.append(s.charAt(i));
                i++;
            }
            i--;  //经分析得这里要i--;
            String s2=stack1.pop()+stringbuffer2.toString();
            stack1.push(s2);
            continue;
        }
        String s3=stack1.peek().replaceAll(" ","");
        return s3;

    }

    public static void main(String[] args) {
        String s="1[a2[bc]]de3[f]";
        String string = decodeString(s);
        System.out.println(string);

    }
}
